package com.yonyou.cyxdms.basedata.service.service.brand;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.service.excel.*;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.framework.util.http.RestHttpUtil;
import com.yonyou.cyx.function.bean.dto.ImportResultDto;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.*;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonBrandService;
import com.yonyou.cyxdms.basedata.service.constant.BasedataCommonConstants;
import com.yonyou.cyxdms.basedata.service.constant.BasedataDictConstants;
import com.yonyou.cyxdms.basedata.service.dto.option.VsOptionDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.BrandImportDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.BrandModifyDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.BrandQueryDTO;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.GeneralBrandDTO;
import com.yonyou.cyxdms.basedata.service.entity.basedata.SystemParamPO;
import com.yonyou.cyxdms.basedata.service.entity.brand.BrandPO;
import com.yonyou.cyxdms.basedata.service.entity.code.CodePO;
import com.yonyou.cyxdms.basedata.service.entity.color.ColorPO;
import com.yonyou.cyxdms.basedata.service.repository.basedata.SystemParamMapper;
import com.yonyou.cyxdms.basedata.service.repository.brand.BrandMapper;
import com.yonyou.cyxdms.basedata.service.repository.color.ColorMapper;
import com.yonyou.cyxdms.basedata.service.repository.configurer.PackageMapper;
import com.yonyou.cyxdms.basedata.service.repository.model.ModelMapper;
import com.yonyou.cyxdms.basedata.service.repository.series.SeriesMapper;
import com.yonyou.cyxdms.basedata.service.service.color.ColorService;
import com.yonyou.cyxdms.basedata.service.service.configure.PackageService;
import com.yonyou.cyxdms.basedata.service.service.model.ModelService;
import com.yonyou.cyxdms.basedata.service.service.option.VsOptionService;
import com.yonyou.cyxdms.basedata.service.service.series.SeriesService;
import com.yonyou.cyxdms.basedata.service.util.MQUtils;
import com.yonyou.cyxdms.basedata.service.util.MapUtils;
import com.yonyou.cyxdms.basedata.service.vo.CarbrandInfoVO;
import com.yonyou.cyxdms.basedata.service.vo.IntentCarCMSVO;
import com.yonyou.cyxdms.basedata.service.vo.IntentCarVo;
import com.yonyou.cyxdms.basedata.service.vo.brand.BrandDictVO;
import com.yonyou.cyxdms.basedata.service.vo.brand.VehicleProductBrandVO;
import com.yonyou.cyxdms.basedata.service.vo.brand.VehicleProductDcsBrandVO;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.framework.constants.FrameworkDictCodeConstants;
import com.yonyou.cyxdms.sysmanage.client.service.login.DealerBrandService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 品牌
 *
 * @author renwd
 * @since 2018/12/7
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class BrandServiceImpl extends ServiceImpl<BrandMapper, BrandPO> implements BrandService {

    //日志对象
    public static final Logger logger = LoggerFactory.getLogger(BrandServiceImpl.class);

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SeriesMapper seriesMapper;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private PackageMapper packageMapper;

    @Autowired
    private ExcelGenerator excelService;

    @Autowired
    private ExcelRead<BrandImportDTO> excelBrandService;

    @Autowired
    DealerBrandService dealerBrandService;

    @Autowired
    private SystemParamMapper systemParamMapper;

    @Autowired
    private IRemoteInvoke iRemoteInvoke;

    @Autowired
    private ColorMapper colorMapper;

    @Autowired
    private RedisClient redisClient;

    @Qualifier("restTemplateNoLb")
    @Autowired
    RestTemplate restTemplate;

	@Autowired
	private SeriesService seriesService;

	@Autowired
	private ModelService modelService;

	@Autowired
	private PackageService packageService;

	@Autowired
	private VsOptionService optionService;

	@Autowired
	private ColorService colorService;

    @Autowired
    BaseCommonBrandService baseCommonBrandService;

	/**
     * 按条件查询品牌信息
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.BrandCacheVO>
     * @author renwd
     * @since 2018/12/7
     */
    @Override
    @Transactional(readOnly = true)
    public List<BrandCacheVO> queryBrandByCondition(Map<String, Object> queryParam) {
        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        return brandMapper.queryBrandByCondition(queryParam);
    }

    /**
     * 根据DEALER_CODE查询所有的品牌信息
     *
     * @param
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.BrandCacheVO>
     * @author guorp
     * @since 2018/12/13
     */
    @Override
    public List<BrandCacheVO> getBrand() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return brandMapper.getBrand(loginInfo.getGroupCode(), loginInfo.getAppId());
    }

    /**
     * 根据查询条件返回对应的品牌数据（pc）
     *
     * @param brandQueryDTO
     * @author Tansj
     * @since 2019/11/14
     */
    @Override
    public IPage<VehicleProductBrandVO> queryVehicleProductBrand(Page page, BrandQueryDTO brandQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = brandQueryDTO.toMaps();
        queryParam = setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询品牌IPage的queryParam:------------------{}", queryParam);
        /**
         * 品牌数据放置redis
         */
        String appId = loginInfoDto.getAppId();
        String  messageFormat = MessageFormat.format(BasedataCommonConstants.BRAND_CACHE_PRODUCT_BRANDID, appId);
        Object brandData = redisClient.get(messageFormat);
        if (null == brandData) {
            LambdaQueryWrapper<BrandPO> brandParam = new QueryWrapper<BrandPO>().lambda();
            brandParam.eq(BrandPO::getAppId, appId).orderByAsc(BrandPO::getBrandCode,BrandPO::getIsDeleted);
            List<BrandPO> brandList = brandMapper.selectList(brandParam);
            List<BrandCacheVO> brandVOList = BeanMapperUtil.copyList(brandList, BrandCacheVO.class);
            redisClient.set(messageFormat, JSONUtil.objectToJson(brandVOList), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
        }
        page.setRecords(brandMapper.queryVehicleProductBrand(page, queryParam));
        return page;
    }

    /**
     * dcs根据查询条件返回对应的品牌数据
     *
     * @param page
     * @param queryParam
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.yonyou.cyxdms.basedata.service.vo.brand.VehicleProductDcsBrandVO>
     * @author renwd
     * @since 2019/7/18
     */
    @Override
    public IPage<VehicleProductDcsBrandVO> queryVehicleProductDcsBrand(Page page, Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfo.getOrgType());
//        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
//        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        page.setRecords(brandMapper.queryDcsVehicleProductBrand(page, queryParam));
        return page;
    }

    /**
     * 下拉框显示品牌
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.brand.BrandDictVO>
     * @author renwd
     * @since 2019/7/16
     */
    @Override
    public List<BrandDictVO> queryBrandDict(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfo.getOrgType());
        return brandMapper.queryBrandDict(queryParam);
    }

    /**
     * dcs品系型新增编辑品牌下拉框（厂端有效）
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.brand.BrandDictVO>
     * @author renwd
     * @since 2019/7/19
     */
    @Override
    public List<BrandDictVO> queryDcsBrandDict(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put("isValid", BaseDataDictConstants.IS_VALID);
        queryParam.put(BasedataCommonConstants.DATA_SOURCES, BasedataDictConstants.DATA_SOURCES_BY_GROUP);
        return brandMapper.queryDcsBrandDict(queryParam);
    }

    /**
     * 新增品牌
     *
     * @param brandDto
     * @author Tansj
     * @since 2019/11/14
     */
    @Override
    public Integer addBrand(BrandModifyDTO brandDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<BrandPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(BrandPO::getAppId, loginInfoDto.getAppId())
                .in(BrandPO::getOwnerCode, loginInfoDto.getOwnerCode())
                .and(obj ->
                        obj.eq(BrandPO::getBrandCode, brandDto.getBrandCode())
                                .or()
                                .eq(BrandPO::getBrandName, brandDto.getBrandName()));
        // 判断同一家店面中是否存在相同的品牌代码或名称
        List<BrandPO> brandPos = brandMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(brandPos)) {
            throw new ServiceBizException(BasedataCommonConstants.BRAND_NOT_REPEAT);
        }
        BrandPO brandPo = BeanMapperUtil.copyProperties(brandDto, BrandPO.class);
        int insertSize = brandMapper.insert(brandPo);
        // 发送消息到MQ
        sendBrand(brandPo, BasedataCommonConstants.BIZ_BRAND_INSERT);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.BRAND_CACHE_BRAND_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        redisClient.del(messageFormat);

        return insertSize;
    }

    /**
     * 新增dcs品牌
     *
     * @param brandDto
     * @author Tansj
     * @since 2019/11/14
     */
    @Override
    public Integer addDcsBrand(BrandModifyDTO brandDto) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        QueryWrapper<BrandPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(BrandPO::getAppId, appId)
                .and(obj ->
                        obj.eq(BrandPO::getBrandCode, brandDto.getBrandCode()));
        // 判断同一家店面中是否存在相同的品牌代码或名称
        List<BrandPO> brandPos = brandMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(brandPos)) {
            return 0;
        }
        BrandPO brandPo = BeanMapperUtil.copyProperties(brandDto, BrandPO.class);
        brandPo.setDataSources(BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        brandPo.setIsVehicleSalesBrand(BasedataDictConstants.IS_VALID);
        brandPo.setAppId(BasedataCommonConstants.APP_ID_RL);
        brandPo.setCompanyCode("-1");
        brandPo.setOwnerCode("-1");
        brandPo.setOwnerParCode("-1");
        brandPo.setIsIssue(BasedataDictConstants.IS_NO_SEND);

        int insertSize = brandMapper.insert(brandPo);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.BRAND_CACHE_BRAND_ALL, appId, groupCode);
        redisClient.del(messageFormat);
        String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, appId, BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
        redisClient.del(productFormat);
        return insertSize;
    }

    /**
     * 品牌发送消息到MQ
     *
     * @param brandPo
     * @author ysj
     * @date 2019/10/23
     */
    public void sendBrand(BrandPO brandPo, String bizId) {
        List<BrandPO> brandList = new ArrayList<>();
        brandList.add(brandPo);
        MQBaseVO<List<BrandPO>> brandMq = new MQBaseVO<>(brandList, brandPo.getAppId(), brandPo.getOwnerCode());
        MQUtils.sendMsg(brandMq.toMap(), bizId, systemParamMapper, iRemoteInvoke);
    }

    /**
     * 修改品牌
     *
     * @param id
     * @param brandDto
     * @author Tansj
     * @since 2019/11/14
     */
    @Override
    public Integer modifyBrand(Long id, BrandModifyDTO brandDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        BrandPO brandPo = brandMapper.selectById(id);
        if (brandPo != null) {
            QueryWrapper<BrandPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .in(BrandPO::getOwnerCode, loginInfoDto.getOwnerCode(), -1)
                    .eq(BrandPO::getAppId, loginInfoDto.getAppId())
                    .notIn(BrandPO::getBrandId, id)
                    .and(obj ->
                            obj.eq(BrandPO::getBrandCode, brandDto.getBrandCode())
                                    .or()
                                    .eq(BrandPO::getBrandName, brandDto.getBrandName()));
            // 判断同一家店面中是否存在相同的品牌代码或名称
            List<BrandPO> brandPos = brandMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(brandPos)) {
                throw new ServiceBizException(BasedataCommonConstants.BRAND_NOT_REPEAT);
            } else {
                brandPo.setBrandCode(brandDto.getBrandCode());
                brandPo.setBrandName(brandDto.getBrandName());
                brandPo.setDataSources(brandDto.getDataSources());
                brandPo.setIsValid(brandDto.getIsValid());
                brandPo.setIsVehicleSalesBrand(brandDto.getIsVehicleSalesBrand());
                brandPo.setRecordVersion(brandDto.getRecordVersion());
                brandPo.setStartDate(brandDto.getStartDate());
                brandPo.setUpdatedAt(LocalDateTime.now());
                int updateSize = brandMapper.updateById(brandPo);
                if (updateSize == 0) {
                    throw new ServiceBizException(BasedataCommonConstants.UPDATE_FAILED);
                }
                // 发送消息到MQ
                sendBrand(brandPo, BasedataCommonConstants.BIZ_BRAND_UPDATE);
                // 删除redis缓存
                String messageFormat = MessageFormat.format(BaseDataCommonConstants.BRAND_CACHE_BRAND_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
                redisClient.del(messageFormat);
                String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, loginInfoDto.getAppId(), BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
                redisClient.del(productFormat);
                return updateSize;
            }
        } else {
            throw new ServiceBizException("后台不存在该品牌！");
        }
    }

    /**
     * dcs修改品牌
     *
     * @param id
     * @param brandDto
     * @return java.lang.Integer
     * @author lijun
     * @since 2019/7/19
     */
    @Override
    public Integer modifyDcsBrand(Long id, BrandModifyDTO brandDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<BrandPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BrandPO::getBrandName, brandDto.getBrandName())
                .in(BrandPO::getOwnerCode, loginInfoDto.getGroupCode(), "-1");
        BrandPO brandPo = brandMapper.selectOne(queryWrapper);
        if (!StringUtils.isNullOrEmpty(brandPo) && !StringUtils.isEquals(brandPo.getBrandCode(), brandDto.getBrandCode())) {
            throw new ServiceBizException(BasedataCommonConstants.BRAND_NOT_REPEAT);
        }

        brandDto.setDataSources(BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        return modifyBrand(id, brandDto);
    }

    @Override
    public List<CarbrandInfoVO> queryCarbrandInfo(String appId) {
        logger.debug("获取品牌开始");
        // 获取经销商id
        logger.info("参数列表：appId:{}", appId);
        // 查询系统参数表 - 品牌转发URL
        SystemParamPO systemParamPo = queryRedirectUrl(appId, BasedataCommonConstants.QUERY_BRAND);
        List<CarbrandInfoVO> carbrandInfoVos = new ArrayList<>();
        if (systemParamPo != null) {
            String url = systemParamPo.getParamValue();
            String response = getRedirectResponse(appId, url);
            logger.info("response:-----------------{}", response);
            Map<String, Object> map = JSONUtil.jsonToMap(response);
            return JSONUtil.jsonToList(JSONUtil.objectToJson(map.get("data")), CarbrandInfoVO.class);
        } else {
            List<BrandDictVO> brandDictVos = brandMapper.allBrands(appId);
            logger.debug("查询结果：brandDictVOS:{}", brandDictVos);
            for (BrandDictVO brand : brandDictVos) {
                if (brand != null) {
                    CarbrandInfoVO carbrandInfoVO = new CarbrandInfoVO();
                    carbrandInfoVO.setBrandId(Long.parseLong(String.valueOf(brand.getBrandId())));
                    carbrandInfoVO.setBrandName(brand.getBrandName());
                    carbrandInfoVos.add(carbrandInfoVO);
                }
            }
            logger.debug("返回前端的品牌信息：{}", carbrandInfoVos);
        }
        return carbrandInfoVos;
    }

    /**
     * 查询系统参数表转发URL
     *
     * @param appId
     * @param paramCode
     * @author Tansj
     * @since 2019/11/26
     */
    @Override
    public SystemParamPO queryRedirectUrl(String appId, String paramCode) {
        LambdaQueryWrapper<SystemParamPO> querySystemParam = new QueryWrapper<SystemParamPO>().lambda();
        querySystemParam.eq(SystemParamPO::getAppId, appId)
                .eq(SystemParamPO::getParamCode, paramCode);
        return systemParamMapper.selectOne(querySystemParam);
    }

    /**
     * 获取转发后的响应数据
     *
     * @param appId
     * @param url
     * @author houkh
     * @since 2019/11/26
     */
    @Override
    public String getRedirectResponse(String appId, String url) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        HttpHeaders httpHeaders = new HttpHeaders();
        Map<String, Object> queryCondition = new HashMap<>();
        httpHeaders.set("appId", appId);
        String messageFormat = MessageFormat.format(com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants.SUB_JWT, appId, ApplicationContextHelper.getBeanByType(LoginInfoDto.class).getUserId());
        Object jwt = redisClient.get(messageFormat);
        logger.debug("从缓存中取得的子系统jwt:key-->{},value-->{}", messageFormat, jwt);
        if (jwt != null) {
            httpHeaders.set("jwt", String.valueOf(jwt));
            httpHeaders.set("userAgent", StringUtils.isEquals(loginInfoDto.getLoginWay(), String.valueOf(FrameworkDictCodeConstants.LOGIN_WAY_PC)) ? "pc" : "app");
        }
        logger.info("转发地址:-----------------{},{}", url, httpHeaders);
        return RestHttpUtil.get(queryCondition, httpHeaders, restTemplate, url, String.class);
    }

    /**
     * 导出
     *
     * @param queryParam
     * @param request
     * @param response
     * @return void
     * @author renwd
     * @since 2019/7/12
     */
    @Override
    public void exportExcelForBrand(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfoDto.getOwnerCode(), loginInfoDto.getAppId(), loginInfoDto.getGroupCode());
        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        List<Map> resultList = brandMapper.selectBrandForExport(queryParam);

        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("品牌信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();
        exportColumnList.add(new ExcelExportColumn("BRAND_CODE", "品牌代码"));
        exportColumnList.add(new ExcelExportColumn("BRAND_NAME", "品牌名称"));
        exportColumnList.add(new ExcelExportColumn("IS_VEHICLE_SALES_BRAND", "是否整车销售品牌", ExcelDataType.Dict));
        exportColumnList.add(new ExcelExportColumn("IS_VALID", "是否有效", ExcelDataType.Dict));
        excelService.generateExcel(excelData, exportColumnList, "品牌信息.xls", request, response);
    }

    /**
     * 品系型查询界面品牌下拉框（厂端所有）
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.brand.BrandDictVO>
     * @author renwd
     * @since 2019/7/17
     */
    @Override
    public List<BrandDictVO> queryBrandsAll(Map<String, Object> queryParam) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        setLoginInfoParam(queryParam, loginInfoDto);
        return brandMapper.queryBrandsAll(queryParam);
    }

    /**
     * @author ：quankk
     * @date ：2019/7/19 17:28
     * @description：
     */
    @Override
    public List<Map> queryBrand2(Map<String, Object> queryParam) {
        return brandMapper.queryBrand2(queryParam);
    }

    /**
     * 判断品牌是否存在
     *
     * @param brandName
     * @return com.yonyou.cyxdms.basedata.service.entity.brand.BrandPO
     * @author renwd
     * @since 2019/7/22
     */
    @Override
    public BrandPO existsBrand(String brandName) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<BrandPO> brandPoQueryWrapper = new QueryWrapper<>();
        brandPoQueryWrapper.lambda().eq(BrandPO::getBrandName, brandName)
                .eq(BrandPO::getAppId, loginInfoDto.getAppId())
                .in(BrandPO::getOwnerCode, loginInfoDto.getOwnerCode(), loginInfoDto.getGroupCode(), "-1");
        BrandPO brandPo = brandMapper.selectOne(brandPoQueryWrapper);
        if (StringUtils.isNullOrEmpty(brandPo)) {
            throw new ServiceBizException("品牌名称不存在");
        }
        return brandPo;
    }

    /**
     * 品牌导入
     *
     * @param importFile
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.BrandImportDTO>
     * @author renwd
     * @since 2019/7/22
     */
    @Override
    public List<BrandImportDTO> importBrand(MultipartFile importFile) {
        ImportResultDto<BrandImportDTO> importResult;
        try {
            importResult = excelBrandService.analyzeExcelFirstSheet(importFile,
                    new AbstractExcelReadCallBack<>(BrandImportDTO.class, this::addbrandImport));
            return importResult.getDataList();
        } catch (IOException e) {
            logger.error("import error:{}", e);
        }
        return Collections.emptyList();
    }

    /**
     * 品牌导入
     *
     * @param rowDto
     * @return void
     * @author renwd
     * @since 2019/7/22
     */
    private void addbrandImport(BrandImportDTO rowDto, boolean isValidateSucess) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<BrandPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BrandPO::getBrandCode, rowDto.getBrandCode())
                .eq(BrandPO::getAppId, loginInfoDto.getAppId())
                .in(BrandPO::getOwnerCode, loginInfoDto.getOwnerCode(), loginInfoDto.getGroupCode(), "-1");
        List<BrandPO> list = brandMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(list)) {
            throw new ServiceBizException("品牌代码或名称不能重复");
        }

        BrandPO brandPo = new BrandPO();
        String dataSources = rowDto.getDataSources();
        if (StringUtils.isNullOrEmpty(dataSources)) {
            brandPo.setDataSources(null);
        } else if ("店面".equals(dataSources)) {
            brandPo.setDataSources(10451001);
        } else if ("主机厂".equals(dataSources)) {
            brandPo.setDataSources(10451002);
        } else if ("集团".equals(dataSources)) {
            brandPo.setDataSources(10451003);
        } else {
            throw new ServiceBizException("数据来源不存在");
        }

        String isValid = rowDto.getIsValid();
        if (StringUtils.isNullOrEmpty(isValid)) {
            brandPo.setIsValid(null);
        } else if ("是".equals(isValid)) {
            brandPo.setIsValid(10041001);
        } else if ("否".equals(isValid)) {
            brandPo.setIsValid(10041002);
        } else {
            throw new ServiceBizException("是否有效类型不存在");
        }

        String isVehicleSalesBrand = rowDto.getIsVehicleSalesBrand();
        if (StringUtils.isNullOrEmpty(isVehicleSalesBrand)) {
            brandPo.setIsVehicleSalesBrand(null);
        } else if ("是".equals(isVehicleSalesBrand)) {
            brandPo.setIsVehicleSalesBrand(10041001);
        } else if ("否".equals(isVehicleSalesBrand)) {
            brandPo.setIsVehicleSalesBrand(10041002);
        } else {
            throw new ServiceBizException("是否整车销售品牌类型不存在");
        }
        brandPo.setBrandCode(rowDto.getBrandCode());
        brandPo.setBrandName(rowDto.getBrandName());

        if (isValidateSucess) {
            brandMapper.insert(brandPo);
            //发送品牌信息到MQ
            sendBrand(brandPo, BasedataCommonConstants.BIZ_BRAND_INSERT);
        }
    }

    /**
     * @Description: 根据brandCode获取brandName
     * @Param: [appId, brandCode]
     * @Return: com.yonyou.cyxdms.basedata.service.vo.brand.BrandDictVO
     * @Author: lijun
     * @Date: 16:02 2019/8/22
     **/
    @Override
    public BrandDictVO getByCode(String appId, String brandCode) {
        return brandMapper.getByCode(appId, brandCode);
    }

    /**
     * 通过appid与品牌名查品牌id
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/9/6
     */
    @Override
    public Long queryBrandByAppidName(String appId, String brandName) {
        LambdaQueryWrapper<BrandPO> query = new QueryWrapper<BrandPO>().lambda();
        query.eq(BrandPO::getBrandName, brandName);
        query.eq(BrandPO::getAppId, appId);
        List<BrandPO> brandPos = brandMapper.selectList(query);
        return !CommonUtils.isNullOrEmpty(brandPos) ? brandPos.get(0).getBrandId() : null;
    }

    /**
     * 获取code与id映射
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/9/10
     */
    @Override
    public Map<Long, String> queryBrandMapping(String appId) {
        Map<Long, String> resultMap = new HashMap<>();
        LambdaQueryWrapper<BrandPO> query = new QueryWrapper<BrandPO>().lambda();
        query.eq(BrandPO::getAppId, appId);
        List<BrandPO> brandList = brandMapper.selectList(query);
        for (BrandPO brandPo : brandList) {
            resultMap.put(brandPo.getBrandId(), brandPo.getBrandCode());
        }
        return resultMap;
    }

    /**
     * 根据条件查询品牌，车系，车型，配置id列表
     *
     * @param searchCondition
     * @return com.yonyou.cyxdms.basedata.service.vo.VehicleVO
     * @author dengqiang
     * @since 2019/9/17
     */
    @Override
    public VehicleVO getIdListByCondition(String searchCondition) {
        VehicleVO vehicleVO = new VehicleVO();
        List<Long> brandIdList = brandMapper.getIdListByCondition(searchCondition);
        List<Long> seriesIdList = seriesMapper.getIdListByCondition(searchCondition);
        List<Long> modelIdList = modelMapper.getIdListByCondition(searchCondition);
        List<Long> configIdList = packageMapper.getIdListByCondition(searchCondition);
        vehicleVO.setBrandIdList(brandIdList);
        vehicleVO.setSeriesIdList(seriesIdList);
        vehicleVO.setModelIdList(modelIdList);
        vehicleVO.setConfigIdList(configIdList);
        return vehicleVO;
    }

    /**
     * 通用-新增品牌
     *
     * @param generalBrandDtos
     * @return
     */
    @Override
    public void addBrandGeneral(List<GeneralBrandDTO> generalBrandDtos) {
        logger.debug("厂端同步至后台的品牌数据:{}", generalBrandDtos);
        if (CollectionUtils.isNotEmpty(generalBrandDtos)) {
            // 数据不为空遍历存储
            for (GeneralBrandDTO generalBrandDTO : generalBrandDtos) {
                QueryWrapper<BrandPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(BrandPO::getAppId, generalBrandDTO.getAppId())
                        .eq(BrandPO::getSourceId, generalBrandDTO.getSourceId());
                BrandPO oldBrandPo = brandMapper.selectOne(queryWrapper);
                String ownerCode = StringUtils.isBlank(generalBrandDTO.getOwnerCode()) ? "-1" : generalBrandDTO.getOwnerCode();
                // ownerCode设值-1 标记车厂下发
                if (oldBrandPo == null) {
                    // 新增品牌
                    BrandPO brandPo = BeanMapperUtil.copyProperties(generalBrandDTO, BrandPO.class);
                    brandPo.setOwnerCode(ownerCode);
                    brandPo.setCompanyCode(ownerCode);
                    brandPo.setOwnerParCode(ownerCode);
                    brandPo.setSourceChangedAt(LocalDateTime.now());
                    brandPo.setCreatedAt(LocalDateTime.now());
                    logger.debug("开始新增插入品牌数据:{}", brandPo);
                    brandMapper.insert(brandPo);
                } else {
                    // 更新品牌
                    BrandPO brandPo = BeanMapperUtil.copyProperties(generalBrandDTO, BrandPO.class);
                    brandPo.setIsValid(generalBrandDTO.getIsValid());
                    brandPo.setOwnerCode(ownerCode);
                    brandPo.setCompanyCode(ownerCode);
                    brandPo.setOwnerParCode(ownerCode);
                    brandPo.setBrandId(oldBrandPo.getBrandId());
                    brandPo.setUpdatedAt(LocalDateTime.now());
                    brandPo.setCreatedBy("-1");
                    brandPo.setIsDeleted(generalBrandDTO.getIsDeleted() == null ? 0 : generalBrandDTO.getIsDeleted());
                    brandPo.setRecordVersion(oldBrandPo.getRecordVersion());
                    logger.debug("开始更新品牌数据:{}", brandPo);
                    brandMapper.updateById(brandPo);
                }
            }
        } else {
            throw new ServiceBizException("厂端传来的品牌数据的缺失！");
        }
    }

    /**
     * 查询所有相关数据
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/10/17
     */
    @Override
    public Map<String, Object> queryBrandRelatedData(Long brandId, Long modelId, Long seriesId, Long packageId, Long optionId) {
        return brandMapper.queryBrandRelatedData(brandId, modelId, seriesId, packageId, optionId);
    }

    /**
     * 未登陆获取品牌
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<BrandCacheVO> getAllBrandByAppId(String appId) {
        LambdaQueryWrapper<BrandPO> query = new QueryWrapper<BrandPO>().lambda().eq(BrandPO::getAppId, appId);
        List<BrandPO> brandPos = this.brandMapper.selectList(query);
        return BeanMapperUtil.copyList(brandPos, BrandCacheVO.class);
    }

    /**
     * 设置登录信息传参
     *
     * @param: queryParam
     * @auther: Tansj
     * @since: 2019/11/14
     */
    @Override
    public Map<String, Object> setLoginInfoParam(Map<String, Object> queryParam, LoginInfoDto loginInfoDto) {
        queryParam.put(BasedataCommonConstants.APP_ID, loginInfoDto.getAppId());
        queryParam.put(BasedataCommonConstants.OWNER_CODE, loginInfoDto.getOwnerCode());
        queryParam.put(BasedataCommonConstants.GROUP_CODE, loginInfoDto.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfoDto.getOrgType());
        return queryParam;
    }


    @Override
    public Map<String, Object> queryBrandRelatedDataByCode(String brandCode, String modelCode, String seriesCode, String packageCode, String optionCode, String appId) {
        return this.brandMapper.queryBrandRelatedDataByCode(brandCode, modelCode, seriesCode, packageCode, optionCode, appId);
    }

    /**
     * 品系型查询界面品牌下拉框
     *
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public List<BrandDictVO> queryBrandDictAll() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        setLoginInfoParam(queryParam, loginInfoDto);
        return brandMapper.queryBrandDictAll(queryParam);
    }

    /**
     * 新增编辑界面本店面品牌下拉框
     *
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public List<BrandDictVO> queryBrandDictOwner() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam = setLoginInfoParam(queryParam, loginInfoDto);
        // 在新增编辑界面，品牌下拉框为本店面的所有有效品牌（不包括无效）
        queryParam.put(BasedataCommonConstants.IS_VALID, BaseDataDictConstants.IS_VALID);
        return brandMapper.queryBrandDictOwner(queryParam);
    }

    /**
     * 新增编辑界面dcs品牌下拉框
     *
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public List<BrandDictVO> queryDcsBrandDict() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam = setLoginInfoParam(queryParam, loginInfoDto);
        // 在新增编辑界面，品牌下拉框为本店面的所有品牌（不包括无效）
        queryParam.put("isValid", BaseDataDictConstants.IS_VALID);
        queryParam.put(BasedataCommonConstants.DATA_SOURCES, BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        return brandMapper.queryDcsBrandDict(queryParam);
    }

    /**
     * 批量获取车型类数据
     *
     * @author
     * @since 2019/11/15
     */
    @Override
    public Map<Long, IntentCarVo> queryBrandRelatedAll(Map<Long, IntentCarVo> paramArr) {
        Set<Long> keys = paramArr.keySet();

        Map<Long, IntentCarVo> resultMap = new HashMap<>();
        for (Long key : keys) {
            //单个需要获取的数据
            IntentCarVo result = new IntentCarVo();
            IntentCarVo intentCarVo = paramArr.get(key);
            Long brandId = intentCarVo.getBrandId();
            Long serviceId = intentCarVo.getServiceId();
            Long modelId = intentCarVo.getModelId();
            Long packageId = intentCarVo.getPackageId();
            Long optionId = intentCarVo.getOptionId();
            Long colorId = intentCarVo.getColorId();
            Long trimColor = intentCarVo.getTrimColor();

            String serviceCode = intentCarVo.getServiceCode();
            String modelCode = intentCarVo.getModelCode();
            String packageCode = intentCarVo.getPackageCode();
            String optionCode = intentCarVo.getOptionCode();
            String colorCode = intentCarVo.getColorCode();
            String brandCode = intentCarVo.getBrandCode();
            if (null != brandId || null != serviceId || null != modelId || null != packageId || null != optionId || null != colorId) {
                Map<String, Object> mappingId = this.queryBrandRelatedData(brandId, modelId, serviceId, packageId, optionId);
                if (mappingId == null) {
                    resultMap.put(key, result);
                    continue;
                }
                result.setModelId(modelId);
                result.setBrandCode((String) mappingId.get("BRAND_CODE"));
                result.setModelCode((String) mappingId.get("MODEL_CODE"));
                result.setServiceCode((String) mappingId.get("SERIES_CODE"));
                result.setPackageCode((String) mappingId.get("CONFIG_CODE"));
                result.setOptionCode((String) mappingId.get("OPTION_CODE"));
                //查询颜色
                if (null != colorId) {
                    ColorPO colorPo = colorMapper.selectById(colorId);
                    if (null != colorPo) {
                        result.setColorCode(colorPo.getColorCode());
                        result.setColorName(colorPo.getColorName());
                        result.setColorId(colorPo.getColorId().longValue());
                    }
                }
                //查询内饰颜色
                if (null != trimColor) {
                    ColorPO colorPo = colorMapper.selectById(trimColor);
                    if (null != colorPo) {
                        result.setTrimColorName(colorPo.getColorName());
                        result.setTrimColor(colorPo.getColorId().longValue());
                    }
                }
                //name
                result.setBrandName((String) mappingId.get("BRAND_NAME"));
                result.setModelName((String) mappingId.get("MODEL_NAME"));
                result.setServiceName((String) mappingId.get("SERIES_NAME"));
                result.setPackageName((String) mappingId.get("CONFIG_NAME"));
                result.setOptionName((String) mappingId.get("OPTION_NAME"));
                resultMap.put(key, result);
                continue;
            } else if (null != brandCode || null != serviceCode || null != modelCode || null != packageCode || null != optionCode || null != colorCode) {

                String appId = intentCarVo.getAppId();
                if (StringUtils.isNullOrEmpty(appId)) {
                    throw new ServiceBizException("appId is null");
                }


                Map<String, Object> mappingId = this.queryBrandRelatedDataByCode(brandCode, modelCode, serviceCode, packageCode ,optionCode , appId);
                if (mappingId == null) {
                    resultMap.put(key, result);
                    continue;
                }
                Object brandIds = mappingId.get("BRAND_ID");
                Object modelIds = mappingId.get("MODEL_ID");
                Object seriesIds = mappingId.get("SERIES_ID");
                Object packageIds = mappingId.get("PACKAGE_ID");
                Object optionIds = mappingId.get("OPTION_ID");
                result.setBrandId(null == brandIds ? null : Long.parseLong(String.valueOf(brandIds)));
                result.setModelId(null == modelIds ? null : Long.parseLong(String.valueOf(modelIds)));
                result.setServiceId(null == seriesIds ? null : Long.parseLong(String.valueOf(seriesIds)));
                result.setPackageId(null == packageIds ? null : Long.parseLong(String.valueOf(packageIds)));
                result.setOptionId(null == optionIds ? null : Long.parseLong(String.valueOf(optionIds)));
                //颜色
                if (null != colorCode) {
                    ColorPO colorPo = colorMapper.getByCode(appId, colorCode);
                    if (null != colorPo) {
                        result.setColorCode(colorPo.getColorCode());
                        result.setColorName(colorPo.getColorName());
                        result.setColorId(colorPo.getColorId().longValue());
                    }

                }


                //name
                result.setBrandName((String) mappingId.get("BRAND_NAME"));
                result.setModelName((String) mappingId.get("MODEL_NAME"));
                result.setServiceName((String) mappingId.get("SERIES_NAME"));
                result.setPackageName((String) mappingId.get("CONFIG_NAME"));
                result.setOptionName((String) mappingId.get("OPTION_NAME"));
                resultMap.put(key, result);
                continue;
            }

        }
        return resultMap;
    }


    /**
     * 批量获取车型类数据
     *
     * @author
     * @since 2019/11/15
     */
    @Override
    public Map<Long, IntentCarCMSVO> queryBrandRelatedAllCms(Map<Long, IntentCarCMSVO> paramArr) {
        Set<Long> keys = paramArr.keySet();

        //获取全部颜色对象
	    //整理成两个Map（key:colorId,value:obj）,（key:colorCode,value:obj）

        Map<Long, IntentCarCMSVO> resultMap = new HashMap<>();
        for (Long key : keys) {
            //单个需要获取的数据
            IntentCarCMSVO result = new IntentCarCMSVO();
            IntentCarCMSVO intentCarVo = paramArr.get(key);
            Long brandId = intentCarVo.getBrandId();
            Long serviceId = intentCarVo.getServiceId();
            Long modelId = intentCarVo.getModelId();
            Long packageId = intentCarVo.getPackageId();
            Long optionId = intentCarVo.getOptionId();
            Long colorId = intentCarVo.getColorId();
            Long interiorColorId = intentCarVo.getInteriorColorId();

            String serviceCode = intentCarVo.getServiceCode();
            String modelCode = intentCarVo.getModelCode();
            String packageCode = intentCarVo.getPackageCode();
            String optionCode = intentCarVo.getOptionCode();
            String colorCode = intentCarVo.getColorCode();
            String brandCode = intentCarVo.getBrandCode();
            if (null != brandId || null != serviceId || null != modelId || null != packageId || null != optionId || null != colorId) {
                Map<String, Object> mappingId = this.queryBrandRelatedData(brandId, modelId, serviceId, packageId, optionId);
                if (mappingId == null) {
                    resultMap.put(key, result);
                    continue;
                }
                result.setBrandCode((String) mappingId.get("BRAND_CODE"));
                result.setModelCode((String) mappingId.get("MODEL_CODE"));
                result.setServiceCode((String) mappingId.get("SERIES_CODE"));
                result.setPackageCode((String) mappingId.get("CONFIG_CODE"));
                result.setOptionCode((String) mappingId.get("OPTION_CODE"));
                //查询颜色
                if (null != colorId) {
                    ColorPO colorPo = colorMapper.selectById(colorId);
                    if (null != colorPo) {
                        result.setColorCode(colorPo.getColorCode());
                        result.setColorName(colorPo.getColorName());
                        result.setColorId(colorPo.getColorId().longValue());
                    }

                }
                //查询内饰颜色
                if (null != interiorColorId) {
                    ColorPO colorPo = colorMapper.selectById(interiorColorId);
                    if (null != colorPo) {
                        result.setInteriorColorCode(colorPo.getColorCode());
                        result.setInteriorColorName(colorPo.getColorName());
                        result.setInteriorColorId(colorPo.getColorId().longValue());
                    }

                }
                //name
                result.setBrandName((String) mappingId.get("BRAND_NAME"));
                result.setModelName((String) mappingId.get("MODEL_NAME"));
                result.setServiceName((String) mappingId.get("SERIES_NAME"));
                result.setPackageName((String) mappingId.get("CONFIG_NAME"));
                result.setOptionName((String) mappingId.get("OPTION_NAME"));
                resultMap.put(key, result);
                continue;
            } else if (null != brandCode || null != serviceCode || null != modelCode || null != packageCode || null != optionCode || null != colorCode) {

                String appId = intentCarVo.getAppId();
                if (StringUtils.isNullOrEmpty(appId)) {
                    throw new ServiceBizException("appId is null");
                }


                Map<String, Object> mappingId = this.queryBrandRelatedDataByCode(brandCode, modelCode, serviceCode, packageCode ,optionCode , appId);
                if (mappingId == null) {
                    resultMap.put(key, result);
                    continue;
                }
                Object brandIds = mappingId.get("BRAND_ID");
                Object modelIds = mappingId.get("MODEL_ID");
                Object seriesIds = mappingId.get("SERIES_ID");
                Object packageIds = mappingId.get("PACKAGE_ID");
                Object optionIds = mappingId.get("OPTION_ID");
                result.setBrandId(null == brandIds ? null : Long.parseLong(String.valueOf(brandIds)));
                result.setModelId(null == modelIds ? null : Long.parseLong(String.valueOf(modelIds)));
                result.setServiceId(null == seriesIds ? null : Long.parseLong(String.valueOf(seriesIds)));
                result.setPackageId(null == packageIds ? null : Long.parseLong(String.valueOf(packageIds)));
                result.setOptionId(null == optionIds ? null : Long.parseLong(String.valueOf(optionIds)));
                //颜色
                if (null != colorCode) {
                    ColorPO colorPo = colorMapper.getByCode(appId, colorCode);
                    if (null != colorPo) {
                        result.setColorCode(colorPo.getColorCode());
                        result.setColorName(colorPo.getColorName());
                        result.setColorId(colorPo.getColorId().longValue());
                    }

                }


                //name
                result.setBrandName((String) mappingId.get("BRAND_NAME"));
                result.setModelName((String) mappingId.get("MODEL_NAME"));
                result.setServiceName((String) mappingId.get("SERIES_NAME"));
                result.setPackageName((String) mappingId.get("CONFIG_NAME"));
                result.setOptionName((String) mappingId.get("OPTION_NAME"));
                resultMap.put(key, result);
                continue;
            }

        }
        return resultMap;
    }

	@Override
	public Map<String, IntentCarCMSVO> queryBrandRelatedAllCmsOptimization(Map<String, IntentCarCMSVO> paramArr) {
		Set<String> keys = paramArr.keySet();

		LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
		String appid = loginInfo.getAppId();
		//获取全部颜色对象
		//整理成两个Map（key:colorId,value:obj）,（key:colorCode,value:obj）

//		loginInfo.getGroupCode()
		//品牌
		Map<Long,BrandCacheVO> brandIdMap = Maps.newHashMap();
		Map<String,BrandCacheVO> brandCodeMap = Maps.newHashMap();
		List<BrandCacheVO> brandList = getBrand();

		brandList.stream().forEach(e-> {
			brandIdMap.put(e.getBrandId(),e);
			brandCodeMap.put(e.getBrandCode(),e);
		});

		//车系
		Map<Long,SeriesCacheVO> seriesIdMap = Maps.newHashMap();
		Map<String,SeriesCacheVO> seriesCodeMap = Maps.newHashMap();
		List<SeriesCacheVO> seriesList = seriesService.getAllSeriesByAppId(appid);

		seriesList.stream().forEach(e-> {
			seriesIdMap.put(e.getSeriesId(),e);
			seriesCodeMap.put(e.getSeriesCode(),e);
		});

		//车型
		Map<Long,ModelCacheVO> modelIdMap = Maps.newHashMap();
		Map<String,ModelCacheVO> modelCodeMap = Maps.newHashMap();
		List<ModelCacheVO> modelList = modelService.getAllModelByAppId(appid);

		modelList.stream().forEach(e-> {
			modelIdMap.put(e.getModelId(),e);
			modelCodeMap.put(e.getModelCode(),e);
		});

		//配置
		Map<Long,PackageCacheVO> packageIdMap = Maps.newHashMap();
		Map<String,PackageCacheVO> packageCodeMap = Maps.newHashMap();
		List<PackageCacheVO> packageList = packageService.getAllPackageByAppId(appid);

		packageList.stream().forEach(e-> {
			packageIdMap.put(e.getPackageId(),e);
			packageCodeMap.put(e.getConfigCode(),e);
		});

		//选装
		Map<Long,VsOptionDTO> optionIdMap = Maps.newHashMap();
		Map<String,VsOptionDTO> optionCodeMap = Maps.newHashMap();
		List<VsOptionDTO> optionList = optionService.getAllOptionByAppId(appid);

		optionList.stream().forEach(e-> {
			optionIdMap.put(e.getOptionId(),e);
			optionCodeMap.put(e.getOptionCode(),e);
		});

		//颜色
		Map<Long,ColorCacheVO> colorIdMap = Maps.newHashMap();
		Map<String,ColorCacheVO> colorCodeMap = Maps.newHashMap();
		List<ColorCacheVO> colorList = colorService.getAllColorByAppIdAndType(appid,16081002);

		colorList.stream().forEach(e-> {
			colorIdMap.put(e.getColorId(),e);
			colorCodeMap.put(e.getColorCode(),e);
		});

		//内饰颜色
		Map<Long,ColorCacheVO> interiorColorIdMap = Maps.newHashMap();
		Map<String,ColorCacheVO> interiorColorCodeMap = Maps.newHashMap();
		List<ColorCacheVO> interiorColorList = colorService.getAllColorByAppIdAndType(appid,16081001);

		interiorColorList.stream().forEach(e-> {
			interiorColorIdMap.put(e.getColorId(),e);
			interiorColorCodeMap.put(e.getColorCode(),e);
		});

		Map<String, IntentCarCMSVO> resultMap = new HashMap<>();
		for (String key : keys) {
			//单个需要获取的数据
			IntentCarCMSVO result = new IntentCarCMSVO();
			IntentCarCMSVO intentCarVo = paramArr.get(key);
			Long brandId = intentCarVo.getBrandId();
			Long serviceId = intentCarVo.getServiceId();
			Long modelId = intentCarVo.getModelId();
			Long packageId = intentCarVo.getPackageId();
			Long optionId = intentCarVo.getOptionId();
			Long colorId = intentCarVo.getColorId();
			Long interiorColorId = intentCarVo.getInteriorColorId();

			String serviceCode = intentCarVo.getServiceCode();
			String modelCode = intentCarVo.getModelCode();
			String packageCode = intentCarVo.getPackageCode();
			String optionCode = intentCarVo.getOptionCode();
			String colorCode = intentCarVo.getColorCode();
			String brandCode = intentCarVo.getBrandCode();
			if (null != brandId || null != serviceId || null != modelId || null != packageId || null != optionId || null != colorId) {
				//按照ID查询
				//品牌
				BrandCacheVO brandObject = brandIdMap.get(brandId);

				if(brandObject == null){
					brandObject = new BrandCacheVO();
				}
				//车系
				SeriesCacheVO seriesObject = seriesIdMap.get(serviceId);

				if(seriesObject == null){
					seriesObject = new SeriesCacheVO();
				}

				//车型
				ModelCacheVO modelObject = modelIdMap.get(modelId);

				if(modelObject == null){
					modelObject = new ModelCacheVO();
				}
				//配置
				PackageCacheVO packageObject = packageIdMap.get(packageId);

				if(packageObject == null){
					packageObject = new PackageCacheVO();
				}

				//选装
				VsOptionDTO optionObject = optionIdMap.get(optionId);

				if(optionObject == null){
					optionObject = new VsOptionDTO();
				}

				result.setBrandCode(brandObject.getBrandCode());
				result.setServiceCode(seriesObject.getSeriesCode());
				result.setModelCode(modelObject.getModelCode());
				result.setPackageCode(packageObject.getConfigCode());
				result.setOptionCode(optionObject.getOptionCode());

				//查询颜色
				if (null != colorId) {
					//颜色
					ColorCacheVO colorObject = colorIdMap.get(colorId);
					if (null != colorObject) {
						result.setColorCode(colorObject.getColorCode());
						result.setColorName(colorObject.getColorName());
						result.setColorId(colorObject.getColorId().longValue());
					}

				}
				//查询内饰颜色
				if (null != interiorColorId) {
					//内饰颜色
					ColorCacheVO interiorColorObject = interiorColorIdMap.get(interiorColorId);
					if (null != interiorColorObject) {
						result.setInteriorColorCode(interiorColorObject.getColorCode());
						result.setInteriorColorName(interiorColorObject.getColorName());
						result.setInteriorColorId(interiorColorObject.getColorId().longValue());
					}

				}
				//name
				result.setBrandName(brandObject.getBrandName());
				result.setServiceName(seriesObject.getSeriesName());
				result.setModelName(modelObject.getModelName());
				result.setPackageName(packageObject.getConfigName());
				result.setOptionName(optionObject.getOptionName());

				resultMap.put(key, result);
			} else if (null != brandCode || null != serviceCode || null != modelCode || null != packageCode || null != optionCode || null != colorCode) {
				//按照CODE查询
				//品牌
				BrandCacheVO brandObject = brandCodeMap.get(brandCode);
				if(brandObject == null){
					brandObject = new BrandCacheVO();
				}

				//车系
				SeriesCacheVO seriesObject = seriesCodeMap.get(serviceCode);


				if(seriesObject == null){
					seriesObject = new SeriesCacheVO();
				}

				//车型
				ModelCacheVO modelObject = modelCodeMap.get(modelCode);


				if(modelObject == null){
					modelObject = new ModelCacheVO();
				}

				//配置
				PackageCacheVO packageObject = packageCodeMap.get(packageCode);

				if(packageObject == null){
					packageObject = new PackageCacheVO();
				}

				//选装
				VsOptionDTO optionObject = optionCodeMap.get(optionCode);
				if(optionObject == null){
					optionObject = new VsOptionDTO();
				}

				result.setBrandId(brandObject.getBrandId());
				result.setModelId(seriesObject.getSeriesId());
				result.setServiceId(modelObject.getModelId());
				result.setPackageId(packageObject.getPackageId());
				result.setOptionId(optionObject.getOptionId());

				//颜色
				if (null != colorCode) {
					ColorCacheVO colorObject = colorIdMap.get(colorCode);
					if (null != colorObject) {
						result.setColorCode(colorObject.getColorCode());
						result.setColorName(colorObject.getColorName());
						result.setColorId(colorObject.getColorId().longValue());
					}
				}

				result.setBrandName(brandObject.getBrandName());
				result.setServiceName(seriesObject.getSeriesName());
				result.setModelName(modelObject.getModelName());
				result.setPackageName(packageObject.getConfigName());
				result.setOptionName(optionObject.getOptionName());

				resultMap.put(key, result);
			}
		}
		return resultMap;
	}

    @Override
    public IntentCarVo queryUpIntentCar(IntentCarVo intentCarVo) {
        Long brandId = intentCarVo.getBrandId();
        Long serviceId = intentCarVo.getServiceId();
        Long modelId = intentCarVo.getModelId();
        Long packageId = intentCarVo.getPackageId();
        Map<String, Object> resultMap = new HashMap<>();
        if (null == brandId && null == serviceId && null == modelId && null == packageId) {
            return null;
        }
        Integer sige = null;
        Long tempId = null;
        if (packageId != null) {
            sige = 4;
            tempId = packageId;
            resultMap.put("PACKAGE_ID", tempId);
        } else if (modelId != null) {
            sige = 3;
            tempId = modelId;
            resultMap.put("MODEL_ID", tempId);
        } else if (serviceId != null) {
            sige = 2;
            tempId = serviceId;
            resultMap.put("SERIES_ID", tempId);
        } else if (brandId != null) {
            sige = 1;
            tempId = brandId;
            resultMap.put("BRAND_ID", tempId);
        }
        String columen = "BRAND_ID,SERIES_ID,MODEL_ID,PACKAGE_ID";
        Map<Integer, String> table = new HashMap<>();
        table.put(1, "tm_brand");
        table.put(2, "tm_series");
        table.put(3, "tm_model");
        table.put(4, "tm_package");

        String[] columentSplit = columen.split(",");

        for (Integer integer = sige; integer > 0; integer--) {
            StringBuilder temp = new StringBuilder();
            for (int i = 0; i < integer; i++) {
                if (i == integer - 1) {
                    temp.append(columentSplit[i]);
                    continue;
                }
                temp.append(columentSplit[i] + ", ");
            }
            Map<String, Long> map = this.brandMapper.queryUpIntentCar(temp, table.get(integer), columentSplit[integer - 1], tempId);
            Object id = map.get(columentSplit[integer - 2 < 0 ? 0 : integer - 2]);
            if (id == null) {
                break;
            }
            tempId = Long.valueOf(String.valueOf(id));
            resultMap.put(columentSplit[integer - 2 < 0 ? 0 : integer - 2], tempId);
        }
        IntentCarVo intentCarVo1 = new IntentCarVo();
        Object resultBrandId = resultMap.get("BRAND_ID");
        Object resultSeriesId = resultMap.get("SERIES_ID");
        Object resultModelId = resultMap.get("MODEL_ID");
        Object resultPackageId = resultMap.get("PACKAGE_ID");
        intentCarVo1.setBrandId(null != resultBrandId ? Long.valueOf(String.valueOf(resultBrandId)) : null);
        intentCarVo1.setServiceId(null != resultSeriesId ? Long.valueOf(String.valueOf(resultSeriesId)) : null);
        intentCarVo1.setModelId(null != resultModelId ? Long.valueOf(String.valueOf(resultModelId)) : null);
        intentCarVo1.setPackageId(null != resultPackageId ? Long.valueOf(String.valueOf(resultPackageId)) : null);
        return intentCarVo1;
    }

    @Override
    public List<BrandDictVO> queryBrandDictAllNopar() {
        return brandMapper.queryBrandDictAllNopar();
    }
}